<template>
	<view class="r-canvas-component" :class="{'hidden':hidden}">

		<u-mask :show="show" :custom-style="{background: 'rgba(0, 0, 0, 0)'}">
			<canvas v-if="canvas_id" :canvas-id="canvas_id" :id="canvas_id"
				:style="{width:(canvas_width*0.8)+'px',height:(canvas_height*0.8)+'px'}" class="canvas"></canvas>

			<!-- #ifdef MP-WEIXIN  || APP-PLUS -->
			<u-button :custom-style="{width:'80%',marginTop:'20rpx'}" type="success" @click="save('wx')" shape="circle">保存
			</u-button>
			<!-- #endif -->

			<!-- #ifdef H5 -->
			<u-button :custom-style="{width:'80%',marginTop:'20rpx'}" type="success" @click="save('h5')" shape="circle">预览
			</u-button>
			<!-- #endif -->

		</u-mask>

		<u-popup v-model="h5show" mode="center" >
			<image :src="blobs" style="width: 80vw;height: 80vh;">
				</div>
		</u-popup>


	</view>
</template>

<script>
	import rCanvasJS from "./r-canvas.js"
	export default {
		mixins: [rCanvasJS],

		props: {

			image: {
				type: String,
				default: ""
			}
		},
		data() {
			return {
				show: false,
				blobs: "",
				h5show: false
			}
		},


		methods: {
			close() {
				this.show = false
				this.canvas_id = ''
			},
			save(type) {
				if(type=='wx'){
					this.wx();
					return
				}
				if(type=='h5'){
					this.h5(this.image)
					return
				}
			},
			h5(base64){
				var arr = base64.split(',');
				var bytes = atob(arr[1]);
				let ab = new ArrayBuffer(bytes.length);
				let ia = new Uint8Array(ab);
				for (let i = 0; i < bytes.length; i++) {
					ia[i] = bytes.charCodeAt(i);
				}
				var blob = new Blob([ab], {
					type: 'application/octet-stream'
				});
				var url = URL.createObjectURL(blob);
				var a = document.createElement('a');
				a.href = url;
				a.download = new Date().valueOf() + ".png";
				var e = document.createEvent('MouseEvents');
				this.blobs = url;
				e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
				a.dispatchEvent(e);
				URL.revokeObjectURL(url);
				this.h5show = true;
				this.show=false;
			},
			wx(){
				uni.saveImageToPhotosAlbum({
					filePath:this.image,
					success:(res)=> {
						uni.showToast({
							title: '图片保存成功',
							icon: 'none',
						});
						this.show=false  	
								this.canvas_id=''
					},
					fail: function(e) {
						console.log(e);
						uni.showToast({
							title: '图片保存失败',
							icon: 'none',
						});
					}
				})
			}
			
		},

	}
</script>
<style>
	.r-canvas-component.hidden {
		position: fixed;
		top: -5000upx;
	}

	.canvas {
		position: relative;
		left: 10%;
		margin-top: 10%;
	}
</style>
